package com.example.jbmsuppliers.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.example.jbmsuppliers.sinopec.activity.LoginActivity;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import static com.example.jbmsuppliers.sinopec.Constant.WX_APP_ID;
import static com.example.jbmsuppliers.sinopec.Constant.WX_CODE;
import static com.example.jbmsuppliers.sinopec.activity.LoginActivity.isWXLogin;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IWXAPI api = WXAPIFactory.createWXAPI(this,WX_APP_ID, true);
		api.handleIntent(getIntent(), this);
	}

	@Override
	public void onReq(BaseReq req) {
		finish();
	}

	@Override
	public void onResp(BaseResp resp) {
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			if (isWXLogin) {
				SendAuth.Resp sendResp = (SendAuth.Resp) resp;
				WX_CODE = "";
				if (WX_CODE.equals("")) {
					WX_CODE = sendResp.code;

				}
				finish();
				sendBroadcast(new Intent("IS_WEIXIMN"));
			}
             else {
				Toast.makeText(this, "微信授权成功!", Toast.LENGTH_SHORT).show();
				finish();
			}
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
           isWXLogin = false;
			sendBroadcast(new Intent("IS_WEIXIMN"));
			Toast.makeText(this,"微信授权已取消!", Toast.LENGTH_SHORT).show();
			finish();
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
        isWXLogin = false;
			sendBroadcast(new Intent("IS_WEIXIMN"));
			Toast.makeText(this,"微信授权被拒绝", Toast.LENGTH_SHORT).show();
			finish();
			break;
		default:
			isWXLogin = false;
			sendBroadcast(new Intent("IS_WEIXIMN"));
			Toast.makeText(this,"授权失败请重新登录!", Toast.LENGTH_SHORT).show();

			break;
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		LoginActivity.wxApi.handleIntent(intent, this);
		finish();
	}
}
